import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { api } from '@/lib/apiService';

export async function GET(request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    
    // 从URL中获取参数
    const { searchParams } = new URL(request.url);
    const tag = searchParams.get('tag');
    const title = searchParams.get('title');
    
    // 构建查询参数
    const queryParams = new URLSearchParams();
    if (tag) queryParams.append('tag', tag);
    if (title) queryParams.append('title', title);
    
    // 调用Python后端的提示词API - 使用带认证的方法
    const response = await api.auth.get(`prompts?${queryParams.toString()}`);
    
    return NextResponse.json(response);
  } catch (error) {
    console.error('Database error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}

export async function POST(request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }
    
    const data = await request.json();
    
    // 调用Python后端的创建提示词API - 使用带认证的方法
    const response = await api.auth.post('prompts', data);
    
    return NextResponse.json(response);
  } catch (error) {
    console.error('Server error:', error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}